package com.itfetter.pay.controller;


import cn.hutool.core.bean.BeanUtil;
import com.itfetter.common.exception.BizIllegalException;
import com.itfetter.common.utils.BeanUtils;
import com.itfetter.pay.domain.dto.PayApplyDTO;
import com.itfetter.pay.domain.dto.PayOrderDto;
import com.itfetter.pay.domain.dto.PayOrderFormDTO;
import com.itfetter.pay.domain.po.PayOrder;
import com.itfetter.pay.domain.vo.PayOrderVO;
import com.itfetter.pay.enums.PayType;
import com.itfetter.pay.service.IPayOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 支付相关接口
 */
@RestController
@RequestMapping("pay-orders")
@RequiredArgsConstructor
public class PayController {

    private final IPayOrderService payOrderService;

    /**
     * 生成支付单
     *
     * @param applyDTO 支付单实体对象
     * @return
     */
    @PostMapping
    public String applyPayOrder(@RequestBody PayApplyDTO applyDTO) {
        if (!PayType.BALANCE.equalsValue(applyDTO.getPayType())) {
            // 目前只支持余额支付
            throw new BizIllegalException("抱歉，目前只支持余额支付");
        }
        return payOrderService.applyPayOrder(applyDTO);
    }

    /**
     * 尝试基于用户余额支付
     *
     * @param id              支付单id
     * @param payOrderFormDTO 支付单实体对象
     */
    @PostMapping("{id}")
    public void tryPayOrderByBalance(@PathVariable("id") Long id, @RequestBody PayOrderFormDTO payOrderFormDTO) {
        payOrderFormDTO.setId(id);
        payOrderService.tryPayOrderByBalance(payOrderFormDTO);
    }

    /**
     * 查询支付单
     *
     * @return
     */
    @GetMapping
    public List<PayOrderVO> queryPayOrders() {
        return BeanUtils.copyList(payOrderService.list(), PayOrderVO.class);
    }

    @GetMapping("/biz/{id}")
    public PayOrderDto queryPayOrderByBizOrderNo(@PathVariable("id") Long bizOrderNo) {
        PayOrder payOrder = payOrderService.lambdaQuery().eq(PayOrder::getBizOrderNo, bizOrderNo).one();
        PayOrderDto payOrderDto = BeanUtils.copyBean(payOrder, PayOrderDto.class);
        return payOrderDto;
    }
}
